package com.guojian.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.annotation.Nullable;

import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.SqlProvider;

public class PreparedStatementCreatorFactory {

	private boolean returnGeneratedKeys = false;

	@Nullable
	private String[] generatedKeysColumnNames;

	private class PreparedStatementCreatorImpl implements PreparedStatementCreator, PreparedStatementSetter, SqlProvider {

		private String sql;
		private Object[] params;

		public PreparedStatementCreatorImpl(String sql, Object[] params) {
			super();
			this.sql = sql;
			this.params = params;
		}

		@Override
		public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
			PreparedStatement ps = null;
			if (generatedKeysColumnNames != null || returnGeneratedKeys) {
				if (generatedKeysColumnNames != null && generatedKeysColumnNames.length > 0) {
					ps = con.prepareStatement(this.sql, generatedKeysColumnNames);
				} else {
					ps = con.prepareStatement(this.sql, PreparedStatement.RETURN_GENERATED_KEYS);
				}
			} else {
				ps = con.prepareStatement(this.sql);
			}
			setValues(ps);
			return ps;
		}

		@Override
		public void setValues(PreparedStatement ps) throws SQLException {
			for (int j = 0; j < this.params.length; j++) {
				ps.setObject(j + 1, this.params[j]);
			}
		}

		@Override
		public String getSql() {
			return this.sql;
		}

	}

	public void setReturnGeneratedKeys(boolean returnGeneratedKeys) {
		this.returnGeneratedKeys = returnGeneratedKeys;
	}

	public boolean isReturnGeneratedKeys() {
		return (generatedKeysColumnNames != null && generatedKeysColumnNames.length > 0) || returnGeneratedKeys;
	}

	public void setGeneratedKeysColumnNames(String[] generatedKeysColumnNames) {
		this.generatedKeysColumnNames = generatedKeysColumnNames;
	}

	public PreparedStatementCreator getPreparedStatementCreator(String sql, Object[] params) {
		return new PreparedStatementCreatorImpl(sql, params);
	}

}
